<template>
  <div>
    <!--新建工单-->
    <Modal :mask-closable="false" v-model="deviceVisible" width="800" :title="titleTop" class="modal-content-layout">
      <Form ref="deviceForm" :model="formTop" label-position="top" :rules="validateDevice">
        <Row :gutter="16">
          <Col :span="12">
          <!--设备编号-->
          <FormItem :label="$t('equipCheck.EquipmentNo')" prop="deviceNo">
            <Select v-model="formTop.deviceNo" filterable clearable v-if="titleTop!=='编辑工单'"
              :placeholder="`${$t('common.inputInfo')}${$t('equipCheck.SerialNo')}`" :remote-method="handleRemote"
              :loading="searchLoading" @on-select="handleChangeWl">
              <Option v-for="(item, i) in numberList" :value="item.deviceNo" :disabled="item.disabled" :label="item.desc"
                :key="i">
              </Option>
            </Select>
              <Input v-else v-model="formTop.deviceNo"
              clearable disabled />
          </FormItem>
          </Col>
          <Col :span="12">
          <!--设备流水号-->
          <FormItem :label="$t('equipCheck.SerialNo')">
            <Input v-model="formTop.deviceMId" disabled
              :placeholder="`${$t('common.inputInfo')}${$t('equipCheck.EquipmentNo')}`" clearable />
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
          <!--设备名称-->
          <FormItem :label="$t('spareParts.EquipmentName')" prop="deviceName">
            <Input v-model="formTop.deviceName"
              :placeholder="`${$t('common.inputInfo')}${$t('spareParts.EquipmentName')}`" clearable disabled />
          </FormItem>
          </Col>
          <Col :span="12">
          <!--故障时间-->
          <FormItem :label="$t('fault.FaultTime')" prop="faultTime">
            <DatePicker :options="optionsdate" :disabled="inputEquipmentInfo" v-model="formTop.faultTime" type="datetime"
              format="yyyy-MM-dd HH:mm:ss" :placeholder="`${$t('common.selectInfo')}${$t('fault.FaultTime')}`">
            </DatePicker>
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
          <!--报修时间-->
          <FormItem :label="$t('报修时间')" prop="faultTime">
            <DatePicker :options="optionsdate" disabled v-model="formTop.maintainApplyTime" type="datetime"
              :clearable="false" format="yyyy-MM-dd HH:mm:ss"
              :placeholder="`${$t('common.selectInfo')}${$t('fault.FaultTime')}`">
            </DatePicker>
          </FormItem>
          </Col>
          <Col :span="12">
          <!--报修电话-->
          <FormItem :label="$t('fault.repairPhone')" prop="maintainApplyPhone">
            <Input maxlength="11" :disabled="inputEquipmentInfo"
              :placeholder="`${$t('common.inputInfo')}${$t('fault.PhoneNumber')}`" v-model="formTop.maintainApplyPhone"
              clearable />
          </FormItem>
          </Col>

        </Row>
        <Row :gutter="16">
          <Col :span="12">
          <!--报修人-->
          <FormItem :label="$t('fault.AppliedBy')">
            <Input v-model="formTop.username" clearable disabled />
          </FormItem>
          </Col>
          <Col :span="12">
          <!--维修迫切程度-->
          <FormItem :label="$t('fault.Evergreen')" prop="maintainGrade">
            <Select v-model="formTop.maintainGrade" :disabled="inputEquipmentInfo"
              :placeholder="`${$t('common.selectInfo')}${$t('fault.Evergreen')}`">
              <Option v-for="item in levels" :value="item.value" :label="item.label" :key="item.value">
              </Option>
            </Select>
          </FormItem>
          </Col>

        </Row>
        <Row :gutter="16">
          <Col :span="12">
          <!--是否影响生产-->
          <FormItem :label="$t('fault.ImpactProduction')" prop="affectProductionFlag">
            <RadioGroup v-model="formTop.affectProductionFlag" :disabled="inputEquipmentInfo">
              <Radio :label="item.value" v-for="item in effects" :key="item.value">
                {{ item.label }}
              </Radio>
            </RadioGroup>
          </FormItem>
          </Col>
          <Col :span="12">
          <FormItem :label="$t('故障代码')" prop="faultTypeCode">
            <Select v-model="formTop.faultTypeCode" :placeholder="`${$t('common.selectInfo')}`" clearable>
              <Option v-for="(item, index) in faultCodeList" :value="item.faultTypeCode" :label="item.faultTypeCode"
                :key="index"></Option>
            </Select>
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
          <!--故障现象-->
          <FormItem :label="$t('fault.Description')" prop="faultMessage">
            <Select v-model="formTop.faultMessage" :placeholder="`${$t('common.selectInfo')}`" clearable>
              <Option v-for="(item, index) in faultMessageList" :value="item.value" :label="item.value"
                :key="index"></Option>
            </Select>
            <!-- <searchAndSelectComponent ref="searchAndSelect" v-model="formTop.faultMessage" v-if="deviceVisible" :list="faultMessageList" :field="{ label: 'label', value: 'label' }"
              :remote-method="handleRemotefaultMessage" @change="faultMessageChange" /> -->
          </FormItem>
          </Col>
          <Col :span="12" :style="{ marginTop: '45px', display: 'flex' }">
          <Upload :show-upload-list="false" accept="image/*" :format="['jpg', 'jpeg', 'png']"
            :before-upload="handleBeforeUpload" type="drag" action="" style="display: inline-block;width:58px;">
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <div class="demo-upload-list" v-for="(item, index) in uploadList" :key="index">
            <img :src="util.filePathToUrl(item.filePath)">
            <Icon type="ios-close-circle" class="delIcon" @click="deleteImg(index)" />
          </div>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="default" @click="handleCancel">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="loadingVisible" @click="handleOk">{{ tarGetid ? $t('fault.Submit') :
          $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <commonModal ref="commonModal" />
  </div>
</template>

<script>
import moment from "moment";
import searchAndSelectComponent from '@/components/searchAndSelect.vue'
import commonModal from "@/components/modalTypes/commonModal.vue"
export default {
  name: "addModal",
  components: { searchAndSelectComponent, commonModal },
  data() {
    return {
      optionsdate: {
        disabledDate(date) {
          return date && date.getTime() > Date.now();
        },
      },
      inputEquipmentInfo: false,
      deviceVisible: false,
      loadingVisible: false,
      searchLoading: false,
      isFirst: false,
      isFirst2: false,
      titleTop: this.$t('fault.CreateAWorkOrder'),
      tarGetid: "",
      target: '',
      formTop: {
        deviceMId: "",
        deviceNo: "",
        deviceName: "",
        faultTime: "",
        maintainApplyTime: "",
        faultMessage: "",
        maintainApplyPhone: "",
        maintainGrade: ""
      },
      faultMessageList: [],
      validateDevice: {
        deviceMId: [
          { required: true, message: `${this.$t('common.inputInfo')}${this.$t('equipCheck.SerialNo')}`, trigger: "change" },
        ],
        deviceNo: [
          { required: true, message: `${this.$t('common.inputInfo')}${this.$t('equipCheck.EquipmentNo')}`, trigger: "change" },
        ],
        deviceName: [
          { required: true, message: `${this.$t('common.inputInfo')}${this.$t('spareParts.EquipmentName')}`, trigger: "change" },
        ],
        faultTime: [
          { required: true, type: "date", message: `${this.$t('common.selectInfo')}${this.$t('fault.FaultTime')}`, trigger: "change" },
        ],
        maintainApplyTime: [
          { required: true, type: "date", message: `${this.$t('common.selectInfo')}${this.$t('fault.RenovationTime')}`, trigger: "change" },
        ],
        faultMessage: [
          { required: true, message: `${this.$t('common.inputInfo')}${this.$t('fault.Description')}`, trigger: "change" },
        ],
        maintainApplyPhone: [
          {
            required: false, message: "请输入正确的电话号码",
            pattern: /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/,
            trigger: ["blur"],
            transform(value) {
              return value.trim();
            },
          },

        ],
        maintainGrade: [
          { required: true, type: 'number', message: `${this.$t('common.selectInfo')}${this.$t('fault.Evergreen')}`, trigger: "change" },
        ],
        affectProductionFlag: [
          { required: true, type: 'number', message: `${this.$t('common.selectInfo')}${this.$t('fault.ImpactProduction')}`, trigger: "change" },
        ],
      },
      faultCodeList: [],
      numberList: [],
      numberList2: [],
      levels: [
        { label: "特急", value: 2 },
        { label: "紧急", value: 1 },
        { label: "一般", value: 0 },
      ],
      effects: [
        { label: "影响生产停机", value: 2 },
        { label: "影响生产未停机", value: 1 },
        { label: "不影响生产", value: 0 },
      ],
      uploadList: []
    };
  },
  mounted() {
      this.handleRemotefaultMessage();
  },
  methods: {
    handleRemotefaultMessage(value) {
      this.axios({
        method: 'post',
        url: '/dms/dict/list',
        data: {
          code: "故障现象",
          pageSize: 999,
          pageNo: 1,
          value
        }
      }).then(res => {
        if (res.code === 200) {
          let list = res.data.list || []
          this.faultMessageList = list.map(item => {
            item.label = this.$i18n.locale === 'zh_CN' ? item.value : item.enValue
            return item;
          })
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true })
        }
      })
    },
    faultMessageChange(row) {
      this.formTop.faultMessage = row.label
    },
    getServerDate() {
      this.axios({
        method: 'get',
        url: '/dms/common/date',
      }).then(res => {
        if (res.code === 200) {
          //time
          this.formTop.maintainApplyTime = res.data.time
          this.formTop.faultTime = res.data.time
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }))
        }
      })
    },
    //文件上传
    handleBeforeUpload(file) {
      let formData = new FormData();
      formData.append("dir", 'device')
      formData.append("file", file)
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      this.axios({
        method: 'post',
        url: '/fileServer/upload',
        data: formData,
        config,
      }).then(res => {
        if (res.code == 200) {
          this.uploadList.push({
            fileName: res.data.fileName,
            fileUrl: res.data.fileUrl,
            filePath: res.data.filepath,
          })
        }
      })
      return false;
    },
    deleteImg(index) {
      this.uploadList.splice(index, 1)
    },
    async show(tarGetid) {
      this.target = ""
      this.formTop = {}
      this.$refs.deviceForm.resetFields();
      this.formTop = {
        username: localStorage.getItem("ziyunFactoryPortalName"),
        faultTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        maintainApplyTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        maintainApplyPhone: window.localStorage.getItem('ziyunFactoryUserPhone')
      }
      this.uploadList = []
      this.numberList = []
      this.numberList2 = []
      this.isFirst = false
      this.isFirst2 = false
      this.titleTop = '新建工单'
      if (tarGetid) {
        this.titleTop = this.$t('fault.ApplyForMaintenance')
        this.tarGetid = tarGetid
        this.formTop.deviceMId = tarGetid
        await this.handleRemote(tarGetid)
        this.$nextTick(() => { this.handleChangeWl(tarGetid) })
      }

      this.deviceVisible = true;
    },
    open(formTop, target, title) {
      this.target = target;
      this.formTop = {}
      this.$refs.deviceForm.resetFields();
      this.faultCodeList = []
      const {
        faultTime,
        maintainApplyTime,
      } = formTop;
      this.formTop = {
        ...formTop,
        faultTime: new Date(faultTime),
        maintainApplyTime: new Date(maintainApplyTime),
        username: formTop.maintainApplyByEmpno + '-' + formTop.maintainApplyByStr,
      }

      if (!this.formTop.faultMessage) {
        this.formTop.faultMessage = '无'
      }

      this.inputEquipmentInfo = true;
      this.titleTop = title;

      this.uploadList = []
      this.numberList = []
      this.numberList2 = []
      this.isFirst = false
      this.isFirst2 = false

      this.deviceVisible = true;

      if (!formTop.id) {
        this.getServerDate()
      }

      this.$forceUpdate()
    },
    edit(formTop, target) {
      this.target = target;
      this.$refs.deviceForm.resetFields();
      this.formTop = {
        ...formTop,
        username: formTop.maintainApplyByEmpno + '-' + formTop.maintainApplyByStr,
        faultTime: new Date(formTop.faultTime),
        maintainApplyTime: new Date(formTop.maintainApplyTime),
      }
      
      if (!this.formTop.faultMessage) {
        this.formTop.faultMessage = '无'
      }

      this.inputEquipmentInfo = false;
      this.titleTop = this.$t('编辑工单');

      this.uploadList = this.formTop.attachmentDTOs1;
      this.numberList = []
      this.isFirst = false
      this.isFirst2 = false

      this.deviceVisible = true;
    },
    handleRemote(query) {
      if (query !== "") {
        this.searchLoading = true;
        let _query = query.split('-')
        if (Array.isArray(_query)) _query = _query[0]
        return this.axios({
          method: "post",
          url: "/dms/device/page",
          data: {
            pageSize: 100,
            pageNum:1,
            deviceNo: _query,
            assetsNo: "",
            orgCode: ''
          },
        }).then((res) => {
          if (res.code === 200) {
            this.numberList = res.data.records.map(item => {
              item.desc = item.deviceNo + '-' + item.deviceName
              return item;
            })
            this.numberList.forEach(val => {
              if (val.deviceStatus === '3') {
                val.disabled = true
              }
            })
            if (this.isFirst2) {
              this.formTop.deviceMId = query
            }
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        })
          .finally(() => {
            this.searchLoading = false;
          });
      } else {
        this.numberList = [];
      }
    },
    handleRemote2(query) {
      if (query !== "") {
        this.searchLoading = true;
        this.axios({
          method: "get",
          url: "/dms/dmsDevice/deviceList",
          params: {
            deviceMId: '',
            deviceNo: query,
            orgCode: ''
          },
        })
          .then((res) => {
            if (res.code === 200) {
              this.numberList2 = res.data;
              this.numberList2.forEach(val => {
                if (val.deviceStatus === '3') {
                  val.disabled = true
                }
              })
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true,
              });
            }
          })
          .finally(() => {
            this.searchLoading = false;
          });
      } else {
        this.numberList2 = [];
      }
    },
    handleChangeWl(val) {
      let obj;
      if (this.tarGetid) {
        obj = this.numberList.find(item => item.deviceNo === val)
      } else {
        obj = this.numberList.find(item => item.deviceNo === val.value)
      }
      if (obj) {
        this.formTop.deviceName = obj.deviceName || '';
        this.formTop.deviceNo = obj.deviceNo || '';
        this.formTop.deviceMId = obj.deviceMId || '';
        this.formTop.deviceId = obj.deviceId || '';
        this.isFirst = true
        this.getfaultCode(obj.id)
      }
    },
    getfaultCode(deviceId) {
      let params = {
        deviceId
      }
      console.log(params);
      this.axios({
        method: 'get',
        url: '/dms/devMaintainKb/selectFaultTypeCodeByDeviceId',
        params,
      }).then(res => {
        if (res.code === 200) {
          this.faultCodeList = res.data
        }
      })
    },
    handleChangeWl2(val) {
      if (val) {
        let deviceName = this.numberList2.length ? this.numberList2[val.tag].deviceName : '';
        let deviceMId = this.numberList2.length ? this.numberList2[val.tag].deviceMId : '';
        let deviceId = this.numberList2.length ? this.numberList2[val.tag].deviceId : '';
        this.isFirst2 = true
        this.numberList = [this.numberList2[val.tag]]
        this.formTop = {
          ...this.formTop,
          deviceMId,
          deviceName,
          deviceId,
        }
      }
    },
    handleCancel() {
      this.deviceVisible = false;
      this.loadingVisible = false;
    },
    checkDeviceStatus() {
      return new Promise((resolve) => {
        this.axios({
          method: "get",
          url: "/dms/workOrder/checkDeviceInRepair",
          params: {
            deviceMId: this.formTop.deviceMId
          }
        }).then((res) => {
          if (res.code === 200) {
            resolve(res.data)
          }
        })
      })
    },
    handleOk() {

      console.log(this.formTop)

      let params = {
        deviceMId: this.formTop.deviceMId,
        deviceNo: this.formTop.deviceNo,
        deviceName: this.formTop.deviceName,
        faultTime: this.$moment(this.formTop.faultTime).format("YYYY-MM-DD HH:mm:ss"),
        maintainApplyBy: window.localStorage.getItem("ziyunFactoryUserId"),
        maintainApplyPhone: this.formTop.maintainApplyPhone,
        maintainGrade: this.formTop.maintainGrade,
        faultTypeCode: this.formTop.faultTypeCode,
        affectProductionFlag: this.formTop.affectProductionFlag,
        faultMessage: this.formTop.faultMessage,
        maintainApplyTime: this.$moment(this.formTop.maintainApplyTime).format("YYYY-MM-DD HH:mm:ss"),
        attachmentDTOs: this.uploadList.map(v => ({
          attachmentType: 1,
          ...v
        })),
      };


      this.$refs.deviceForm.validate(async (valid) => {
        if (valid) {

          const createOrder = () => {
            const diff = moment(this.formTop.faultTime).diff(moment(this.formTop.maintainApplyTime), 'seconds')
            if (diff > 0 && this.titleTop!=='编辑工单') {
              this.$Message.warning(`${this.$t('故障时间应小于等于报修时间')}`);
              return
            }

            if (this.inputEquipmentInfo) {
              if (this.target === 'receive') {
                this.$emit('handleRecive', this.formTop, this.formTop.deviceMId);
              } else {
                this.$emit('handleDispath', this.formTop, this.formTop.deviceMId);
              }
              this.handleCancel();
              return;
            }

            this.loadingVisible = true;

            let url = '/dms/deviceMaintenanceWorkOrder/add';
            if (this.target === 'edit') {
              url = '/dms/deviceMaintenanceWorkOrder/edit';
              params['id'] = this.formTop.id
            }

            this.axios({
              method: "post",
              url: url,
              data: params,
            }).then((res) => {
              if (res.code === 200) {
                this.deviceVisible = false;
                this.loadingVisible = false;
                if (this.tarGetid) {
                  this.$Message.success('操作成功！')
                  this.$router.push({ path: '/maintenanceList' })
                } else {
                  this.$Message.success("操作成功！");
                  this.$emit("refresh");
                }
              } else {
                this.deviceVisible = false;
                this.loadingVisible = false;
                this.$Message.error(res.msg);
              }
            }).finally(() => {
              this.formTop = {}
            })
          }

          // if (this.target !=='receive'){
          const _checkDeviceStatus = await this.checkDeviceStatus()
          console.log(_checkDeviceStatus)

          //
          let desc = ''
          if (!this.formTop.id) desc = this.$t('已存在未完工的维修单，是否确认继续报修？')
          if (this.formTop.id) {
            if (this.target === 'receive') {
              desc = this.$t('已存在未完工的维修单，是否确认继续接单？')
            } else {
              desc = this.$t('已存在未完工的维修单，是否确认继续分配？')
            }

          }

          if (_checkDeviceStatus) {
            this.$refs.commonModal.showModal({
              type: "warn",
              desc,
              submit: () => {
                createOrder()
              }
            })
            return;
          } else {
            createOrder()
          }
          // }else{
          //   createOrder()
          // }
        }
      })
    },
  },
};
</script>

<style lang="scss" scoped>
.demo-upload-list {
  position: relative;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border-radius: 4px;
  background: #fff;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  margin-left: 15px;

  img {
    width: 100%;
    height: 100%;
  }

  .delIcon {
    position: absolute;
    right: -10px;
    top: -10px;
    color: red;
    font-size: 20px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
  }
}
</style>
